<template>
  <div class="form-designer">
    <el-container>
      <!-- 左侧字段 -->
      <el-aside :width="leftWidth">
        <div class="fields-container">
          <div class="search">
            <el-input v-model="filterCompText" clearable placeholder="搜索组件名" />
          </div>
          <div class="fields-list">
            <div v-for="(field, index) in fields" :key="index">
              <template v-if="checkExistAppComp(field.list)">
                <div class="field-title">{{ field.title }}</div>
                <draggable
                  tag="ul"
                  :list="field.list"
                  item-key="type"
                  :group="{ name: 'form', pull: 'clone', put: false }"
                  ghost-class="ghost"
                  :sort="false"
                  :clone="clone"
                  @start="(e)=>handleFieldDragStart(e,index)"
                >
                  <template #item="{ element }">
                    <li class="field-label" v-if="element && isAppComp(element)">
                      <a @click="handleFieldClick(element)">
                        <el-icon
                          class="icon"
                          v-if="element.icon"
                        >
                          <component
                            :is="element.icon.replace('icon-','')"
                          />
                        </el-icon>
                        <span>{{ element.compLabel }}</span>
                      </a>
                    </li>
                  </template>
                <!-- <template v-for="(item, cIndex) in field.list">
 
                </template> -->
                </draggable>
              </template>
            </div>
          </div>
        </div>
      </el-aside>
      <!-- 中间主布局 -->
      <el-container class="widget-container" direction="vertical">
        <el-header class="widget-container-header">
          <div class="containBox">
            <template v-if="undoRedo">
              <el-button
                link
                size="default"
                icon="el-icon-refresh-left"
                :disabled="historySteps.index == 0"
                @click="widgetForm = handleUndo()"
                class="btnStyle"
              >撤销
              </el-button>
              <el-button
                link
                size="default"
                icon="el-icon-refresh-right"
                :disabled="historySteps.index == historySteps.steps.length - 1"
                @click="widgetForm = handleRedo()"
              >重做
              </el-button>
            </template>
          </div>
          <div style="display: flex; align-items: center">
            <el-button class="btnStyle" link size="default" @click="regeneration">
              重新生成
            </el-button>
            <el-button
              v-if="toolbar.includes('import')"
              link
              size="default"
              icon="UploadFilled"
              @click="importJsonVisible = true"
              class="btnStyle"
            >导入JSON
            </el-button>
            <el-button
              v-if="toolbar.includes('generate')"
              link
              size="default"
              icon="el-icon-download"
              @click="handleGenerateJson"
              class="btnStyle"
            >生成JSON
            </el-button>
            <el-button
              v-if="toolbar.includes('preview')"
              link
              size="default"
              icon="View"
              @click="handlePreview"
              class="btnStyle"
            >预览
            </el-button>
            <!-- <el-button
              v-if="toolbar.includes('pc')"
              link
              size="default"
              icon="el-icon-monitor"
              @click="showMobile = false"
              class="btnStyle"
            >PC端
            </el-button>
            <el-button
              v-if="toolbar.includes('app')"
              link
              size="default"
              icon="Iphone"
              @click="showMobile = true"
              class="btnStyle"
            >移动端
            </el-button> -->
            <el-button
              v-if="toolbar.includes('clear')"
              class="danger"
              link
              size="default"
              icon="el-icon-delete"
              @click="handleClear"
            >清空
            </el-button>
            <slot name="toolbar"></slot>
          </div>
        </el-header>
        <el-main
          :style="{
            background:
              widgetForm.column.length == 0 && !showMobile
                ? `url(${widgetEmpty}) no-repeat 50%`
                : ''
          }"
        >
          <widget-form
            ref="widgetForm"
            v-model:data="widgetForm"
            v-model:select="widgetFormSelect"
            :showMobile="showMobile"
            :attrList="attrList"
            @change="handleHistoryChange(widgetForm)"
          />
        </el-main>
      </el-container>
      <!-- 右侧配置 -->
      <el-aside class="widget-config-container" :width="rightWidth">
        <el-tabs v-model="configTab" stretch>
          <el-tab-pane label="组件属性" name="widget" style="padding: 0 10px">
            <widget-config
              :formJson="widgetForm"
              v-model:data="widgetFormSelect"
              :inputSelect="inputSelect"
              :notSavedOptions="notSavedOptions"
              :default-values="tempdefaultValues"
              :formModelDataFromDesign="formModelDataFromDesign"
              :fields="fields"
              :attrList="attrList"
            />
          </el-tab-pane>
          <el-tab-pane label="页面属性" name="form" lazy style="padding: 0 10px">
            <form-config :data="widgetForm" :formModelDataFromDesign="formModelDataFromDesign" />
          </el-tab-pane>
          <el-tab-pane label="页面交互" name="lifecycle" lazy style="padding: 0 10px">
            <lifecycle-config :options="widgetForm" v-model="widgetForm.lifecycle" />
          </el-tab-pane>
        </el-tabs>
      </el-aside>
      <!-- 弹窗 -->
      <!-- 导入JSON -->
      <el-drawer
        title="导入JSON"
        v-model="importJsonVisible"
        size="50%"
        append-to-body
        destroy-on-close
      >
        <el-button type="primary" @click="openAIGC" style="margin-bottom: 20px">AIGC生成</el-button>
        <code-editor v-model="importJson" language="json" :languageSelector="false" :themeSelector="false" height="82%" />
        <div class="afd-drawer-foot">
          <el-button size="default" type="primary" @click="handleImportJsonSubmit">确定 </el-button>
          <el-button size="default" type="danger" @click="importJsonVisible = false"
          >取消
          </el-button>
        </div>
      </el-drawer>
      <!-- 生成JSON -->
      <el-drawer
        title="生成JSON"
        v-model="generateJsonVisible"
        size="50%"
        append-to-body
        destroy-on-close
      >
        <code-editor
          v-model="option"
          language="json"
          height="82%"
          :languageSelector="false"
          :themeSelector="false"
          :editor-option="{ readOnly: true }"
        />
        <div class="afd-drawer-foot">
          <el-button size="default" type="primary" @click="handleGenerate">生成 </el-button>

          <el-popover placement="top" trigger="hover" width="350px">
            <el-form
              v-model="configOption"
              style="padding: 0 20px"
              label-suffix="："
              label-width="180px"
              label-position="left"
            >
              <el-form-item label="类型">
                <el-popover
                  placement="top-start"
                  trigger="hover"
                  content="复制json对象"
                  style="margin-right: 15px"
                >
                  <template #reference>
                    <el-radio v-model="configOption.generateType" label="json">json </el-radio>
                  </template>
                </el-popover>
                <el-popover
                  placement="top-start"
                  trigger="hover"
                  content="复制string字符串，可直接用于后端保存无需再次处理。"
                >
                  <template #reference>
                    <el-radio v-model="configOption.generateType" label="string">string </el-radio>
                  </template>
                </el-popover>
              </el-form-item>
              <el-form-item label="缩进长度-空格数量">
                <el-slider
                  v-model="configOption.space"
                  show-stops
                  :marks="{ 1: '1', 2: '2', 3: '3', 4: '4' }"
                  :min="1"
                  :max="4"
                  :step="1"
                />
              </el-form-item>
              <el-form-item label="引号类型">
                <el-switch
                  v-model="configOption.quoteType"
                  active-value="single"
                  inactive-value="double"
                  active-text="单引号"
                  inactive-text="双引号"
                />
              </el-form-item>
              <el-form-item label="移除key的引号">
                <el-switch v-model="configOption.dropQuotesOnKeys" />
              </el-form-item>
              <el-form-item label="移除数字字符串的引号">
                <el-switch v-model="configOption.dropQuotesOnNumbers" />
              </el-form-item>
            </el-form>
            <template #reference>
              <el-button size="default" type="primary" @click="handleCopy" style="margin-left: 10px"
              >复制
              </el-button>
            </template>
          </el-popover>
        </div>
      </el-drawer>
      <!-- 预览 -->
      <el-drawer
        title="预览"
        v-model="previewVisible"
        size="60%"
        append-to-body
        :before-close="handleBeforeClose"
      >
        <form-render
          v-if="previewVisible"
          class="afd-preview-form"
          v-model:data="form"
          :options="option"
          :pageId="pageId"
          @handle-dialog-submit="handlePreviewSubmit"
          ref="form"
        />
        <div class="afd-drawer-foot">
          <el-button size="default" type="primary" @click="handlePreviewSubmit">确定 </el-button>
          <el-button size="default" type="danger" @click="handleBeforeClose">取消 </el-button>
        </div>
      </el-drawer>
    </el-container>
  </div>
</template>

<script>
import { validatenull } from './utils2/index'
import beautifier from './utils2/json-beautifier'
// import MonacoEditor from './utils2/monaco-editor'
import CodeEditor from '@/components/CodeEditor/src/CodeEditor.vue'
import widgetEmpty from './assets/widget-empty.png'
import history from './mixins/history'
import Draggable from 'vuedraggable'
import WidgetForm from './WidgetForm.vue'
import FormConfig from './FormConfig.vue'
import WidgetConfig from './WidgetConfig.vue'
import { cloneDeep } from 'lodash-es'
import FormRender from '@code/components/anvil-code-low-common/views/form-render/index.vue'
import iconFonts from './iconFonts'
import lifecycleConfig from './components/lifecycleConfig.vue'
import {
  searchCompListByUser,
} from '../../api/compbackend'
import { searchTemplateCompList } from '../../api/compont/template'
import { searchCompositeCompList } from '../../api/compont/composite'
import { searchForm } from '@code/components/anvil-code-low-common/api/page'
import { getModelEntityTreeByids } from '@uni/api/uni/entity/info'
import { specialSignTrans, executeFunctionsInOrderByParamsSetting, getJsonCallableCompList, getJsonCallableCompListWithChildren } from '@code/components/anvil-code-low-common/utils/common-methods'
import { useAnvilCodeStore } from '@code/components/anvil-code-low-common/store/modules/code'
import { useCodeStore } from '@code/store'
import EventsMap from '@code/components/anvil-code-low-common/components/EventsMap'
import { ElMessageBox, ElLoading } from 'element-plus'
import { getLocalCompJson } from '@/components/Code'
import { Base64 } from 'js-base64'
import { isBase64 } from '@/utils/zmids'

export default {
  name: 'FormDesign',
  components: {
    Draggable,
    // MonacoEditor,
    WidgetForm,
    FormConfig,
    WidgetConfig,
    FormRender,
    CodeEditor,
    lifecycleConfig
  },
  mixins: [history],
  props: {
    seeData: {
      type: String,
      default: () => '0'
    },
    formModelVersionId: {
      type: String,
      default: () => ''
    },
    pageVersionId: {
      type: String,
      default: () => ''
    },
    options: {
      type: [Object, String],
      default: () => {
        return {
          column: []
        }
      }
    },
    formModelEntities: {
      type: Object,
      default: () => {
        return {
          entities: [],
          isDeploy: ''
        }
      }
    },
    storage: {
      type: Boolean,
      default: false
    },
    asideLeftWidth: {
      type: [String, Number],
      default: '270px'
    },
    asideRightWidth: {
      type: [String, Number],
      default: '380px'
    },
    toolbar: {
      type: Array,
      default: () => {
        return ['import', 'generate', 'preview', 'pc', 'app', 'clear']
      }
    },
    undoRedo: {
      type: Boolean,
      default: true
    },
    defaultValues: {
      type: Object
    },
    formModelDataFromDesign: {
      type: Object,
      default: () => {
        return {
          formModelCode: ''
        }
      }
    },
    forApp: {
      type: Boolean,
      default: false
    },
    formJson: {
      type: String,
      default: () => ''
    }
  },
  data() {
    // 用于记录每个组件出现的次数，用于生成字段名称-序号
    const widgetColumnsMap = new Map()
    return {
      tempdefaultValues: this.defaultValues,
      oaFields: [],
      slotNameArr: [],
      userSlot: '',
      pickerTitle: '请选择人员',
      orgPickerType: 'user',
      orgPickerSelected: [],
      formId: '',
      formData: [],
      inputSelect: [],
      formModelData: {
        entities: {},
        column: [],
        labelPosition: 'right',
        labelSuffix: '：',
        labelWidth: 120,
        gutter: 0,
        menuBtn: true,
        submitBtn: true,
        submitText: '保存',
        emptyBtn: true,
        emptyText: '清空',
        menuPosition: 'center',
        group: []
      },
      defaults: {},
      widgetEmpty,
      // fields,
      // others,
      widgetForm: {
        // iTime: null,
        column: [],
        labelPosition: 'right',
        labelSuffix: '：',
        labelWidth: 120,
        gutter: 0,
        menuBtn: false,
        submitBtn: true,
        submitText: '保存',
        emptyBtn: true,
        emptyText: '清空',
        menuPosition: 'center',
        group: [],
        // submitCheck: [],
        lifecycle: []
      },
      notSavedOptions: [],
      oldNum: {},
      option2: {},
      option: {},
      configTab: 'form',
      widgetFormSelect: {},
      previewVisible: false,
      previewVisibleChild: false,
      generateJsonVisible: false,
      importJsonVisible: false,
      importJson: {},
      iJson1: {},
      form: {},
      form2: {},
      configOption: {
        generateType: 'json',
        space: 2,
        quoteType: 'single',
        dropQuotesOnKeys: true
      },
      history: {
        index: 0, // 当前下标
        maxStep: 20, // 最大记录步数
        steps: [] // 历史步数
      },
      dialogTitle: '',
      isRadio: false,
      typeName: '',
      showMobile: false, // 展示移动端样式,
      iconfontFileContent: '', // 读取iconfont文件内容
      fieldsGroup: [],
      widgetColumnsMap,
      attrList: [],
      allEventsByComps: [],    // 一个包含所有当前组件事件的字符串数组
      filterCompText: '', // 组件筛选文本
      isLine: false,
    }
  },
  computed: {
    pageId() {
      const { getPageId } = useAnvilCodeStore()
      return getPageId
    },
    optionColumn() {
      let arr = []
      this.option.column.forEach((item) => {
        if (item.prop.indexOf('special') != -1 || item.widget) {
          arr.push(item)
        }
      })
      return arr
    },
    previewOption() {
      return this.option
    },
    watchformModelEntities() {
      return this.formModelEntities
    },
    watchFormModelDataFromDesign() {
      return this.formModelDataFromDesign
    },
    leftWidth() {
      if (typeof this.asideLeftWidth == 'string') {
        return this.asideLeftWidth
      } else {
        return `${this.asideLeftWidth}px`
      }
    },
    rightWidth() {
      if (typeof this.asideRightWidth == 'string') {
        return this.asideRightWidth
      } else {
        return `${this.asideRightWidth}px`
      }
    },
    widgetEntities() {
      if (!this.formData.entities) {
        return
      }
      let entity = {}
      for (let key in this.formData.entities) {
        const columns = []
        this.formData.entities[key].columns.forEach((item) => {
          this.filterFieldsNotSystem(item, columns, true)
        })
        entity[key] = { ...this.formData.entities[key], columns }
      }
      return entity
    },
    fields() {
      const originGroup = cloneDeep(this.fieldsGroup)
      return originGroup.filter((group)=>{
        const { list } = group
        const matchList = list.filter(item=>item.compLabel.includes(this.filterCompText))
        if(matchList.length){
          group.list = matchList
          return true
        }else{
          return false
        }
      })
    },
    // 是否为现有表导入模式
    isDataSource() {
      return this.formModelDataFromDesign.modelingFrom == '1'
    },
  },
  watch: {
    watchformModelEntities: {
      async handler(val) {
        await this.getoaFields()
        if (!val.entities || !val.entities.length) {
          return
        }
        // 主从表所有的字段收集
        const fields = []
        val.entities.forEach((e) => {
          const col = e.columns.map((item) => {
            let arr = {}
            arr['value'] = item.formEntityColumnDesc + '(' + item.formEntityColumnName + ')'
            arr['label'] = item.formEntityColumnDesc
            return arr
          })
          fields.push(...col)
        })
        this.inputSelect = [...fields]

        this.formData = this.formModelData
        this.initialization(this.formModelData)
      },
      immediate: true,
      deep: true
    },
    widgetForm: {
      handler(val) {
        this.$emit('changeOptions', val)
        clearTimeout(this.iTime)
        this.iTime = setTimeout(() => {
          let arr = []
          if (val && val.column) {
            val.column.forEach((a) => {
              arr.push(a)
            })
          }
          let newArray = arr.filter(
            (item) => item.type != 'dynamic' && item.type != 'primary' && item.type != 'text'
          )
          this.notSavedOptions = newArray
          // this.$EventBus.$emit('notSavedOptionSubmit', arr)
        }, 500)
      },
      deep: true
    },
    options: {
      handler(val) {
        let options = val
        if (typeof options == 'string') {
          try {
            options = eval('(' + options + ')')
          } catch (e) {
            console.error('非法配置')
            options = { column: [] }
          }
        }
        // 目前在此处注释掉options的接收，后续如果有影响需要改回

        // this.widgetForm = JSON.parse(JSON.stringify(options))
        // this.transAvueOptionsToFormDesigner(options).then((res) => {
        //   this.widgetForm = { ...this.widgetForm, ...res };
        // });
      },
      deep: true
    },
    widgetFormSelect: {
      handler(val) {
        if (val.type && val.type == 'select') {
          this.tempdefaultValues = {
            select: val.dicData
          }
        }

        if (this.configTab == 'form') this.configTab = 'widget'
      },
      deep: true
    },
    previewOption: {
      handler(val) {
        // val.column.forEach((item) => {
        //   if (item.type == 'selects') {
        //     item.type = 'select'
        //   } else if (item.type == 'counter') {
        //     item.type = 'input-number'
        //   }
        // })
      }
    }
  },
  async created() {
    this.getFormJsonEchoByAdd()
    this.getAttrsByEntity()
    this.getAllEventsByComps()
  },
  methods: {
    async getoaFields() {
      const dictRes = await this.getDicts('code_component_group')
      const compTypes = dictRes.data
      await searchCompListByUser().then((res) => {
        const { data } = res
        compTypes.map((dict)=> {
          const { dictLabel, dictValue } = dict
          const list = this.getCompList(data[dictValue])
          if(list.length){
            this.fieldsGroup.push({
            title: dictLabel,
            list: this.getCompList(data[dictValue])
          })
          }
        })
      })

      const templateCompList = await this.getTemplateCompList()
      const compositeCompList = await this.getCompositeCompList()
      this.fieldsGroup.push(
        ...[
          {
            title: '模板组件',
            list: templateCompList.map((comp) => {
              return {
                compLabel: comp.templateName,
                type: 'template',
                ...comp
              }
            })
          },
          {
            title: '复合组件',
            list: compositeCompList.map((comp) => {
              return {
                compLabel: comp.compositeName,
                type: 'composite',
                ...comp
              }
            })
          }
        ]
      )
      const LocalCompJson = getLocalCompJson.map((item)=>{
        const { title, list } = item
        item.list = list.map((comp)=>{
          return {
            compLabel: comp.label,
            ...comp
          }
        })
        return item
      })
      console.log('LocalCompJson',LocalCompJson)
      this.fieldsGroup.push(...LocalCompJson)
    },
    getCompList(data) {
      if(!data){
        return []
      }
      return data.map((item) => {
        const { componentJson, valueType, isApp, chineseDesc } = item
        let compObj = {}
        try {
          compObj = JSON.parse(componentJson)
        } catch (e) {
          console.log('组件json错误', chineseDesc, e)
        }
        return {
          ...compObj,
          valueType,
          isApp,
          compLabel: chineseDesc
        }
      })
    },
    regeneration() {
      this.$confirm('此操作将清空当前所有设计，重新根据数据模型生成页面, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.widgetForm.column = []
          this.form = {}
          this.widgetFormSelect = {}
          this.handleHistoryChange(this.widgetForm)
          this.$message({
            type: 'success',
            message: '重新生成成功!'
          })
          // this.formModelData = this.formData
          this.handleImportJsonSubmit()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          })
        })
    },
    // 组件初始化时加载本地存储中的options(需开启storage),若不存在则读取用户配置的options
    async handleLoadStorage() {
      let options = this.options
      if (typeof options == 'string') {
        try {
          options = eval('(' + options + ')')
        } catch (e) {
          console.error('非法配置')
          options = { column: [] }
        }
      }
      if (!options.column) options.column = []
      this.widgetForm = this.initHistory({
        index: 0,
        maxStep: 20,
        steps: [
          await this.transAvueOptionsToFormDesigner({
            ...this.widgetForm,
            ...options
          })
        ],
        storage: this.storage
      })
      if (this.undoRedo) {
        window.addEventListener(
          'keydown',
          (evt) => {
            // 监听 cmd + z / ctrl + z 撤销
            if (
              (evt.metaKey && !evt.shiftKey && evt.keyCode == 90) ||
              (evt.ctrlKey && !evt.shiftKey && evt.keyCode == 90)
            ) {
              this.widgetForm = this.handleUndo()
            }

            // 监听 cmd + shift + z / ctrl + shift + z / ctrl + y 重做
            if (
              (evt.metaKey && evt.shiftKey && evt.keyCode == 90) ||
              (evt.ctrlKey && evt.shiftKey && evt.keyCode == 90) ||
              (evt.ctrlKey && evt.keyCode == 89)
            ) {
              this.widgetForm = this.handleRedo()
            }
          },
          false
        )
      }
    },
    // 加载icon
    // handleLoadCss() {
    //   const head = document.getElementsByTagName('head')[0]
    //   const script = document.createElement('link')
    //   script.rel = 'stylesheet'
    //   script.type = 'text/css'
    //   script.href = 'https://at.alicdn.com/t/font_1254447_zc9iezc230c.css'
    //   head.appendChild(script)
    //   // this.loadScript('css', 'https://at.alicdn.com/t/font_1254447_zc9iezc230c.css')
    // },
    // Avue文档链接
    handleAvueDoc() {
      window.open('https://avuejs.com/form/form.html', '_blank')
    },
    // 左侧字段点击
    handleFieldClick(item, newIndex) {
      // 同一张表单暂不允许出现两个prop字段相同的项
      if (this.widgetForm.column.find((col) => col.prop === item.prop)) {
        return
      }
      // 有bug，暂时注释掉 2024.1.23
      // this.$refs.widgetForm.handleWidgetAdd({ newIndex });
    },
    // 预览 - 弹窗
    handlePreview() {
      if (!this.widgetForm.column || this.widgetForm.column.length == 0)
        this.$message.error('没有需要展示的内容')
      else {
        // eslint-disable-next-line @typescript-eslint/no-this-alias
        var that = this
        this.transformToAvueOptions(this.widgetForm, true).then((data) => {
          this.checkFlagChild(data, () => {
            this.setRule(data, (ret) => {
              if (ret.initDataUrl && ret.initDataType) {
                if (ret.initDataType == 'get') {
                  getAction(ret.initDataUrl).then((response) => {
                    eval(ret.initDataDetail)
                    this.option = ret
                    console.log('option', this.option)
                    this.previewVisible = true
                  })
                }
              } else {
                let arr = []
                ret.column.map((item) => {
                  if (item.isSystem == 'N' || item.isSystem == undefined) {
                    arr.push(item)
                  }
                })
                ret.column = arr
                this.option = ret
                console.log('option', this.option)
                this.previewVisible = true
              }
            })
          })
        })
      }
    },
    judgeRule(prop, condition, callback) {
      condition.forEach((z) => {
        z.map((x) => {
          if (x.label == prop) {
            callback(z)
          }
        })
      })
    },
    setDatail(ret, all) {
      ret.map((m) => {
        var flag = []
        m.children.map((s) => {
          if (this.form[s.label] == 'undefined') {
            this.form[s.label] = undefined
          }
          switch (s.rule) {
            case '等于':
              if (this.form[s.label] == s.value) {
                flag.push(true)
              } else {
                flag.push(false)
              }
              break
            case '不等于':
              if (this.form[s.label] == s.value) {
                flag.push(false)
              } else {
                flag.push(true)
              }
              break
            case '不包含':
              if (this.form[s.label].indexOf(s.value) != -1) {
                flag.push(false)
              } else {
                flag.push(true)
              }
              break
            case '包含':
              if (this.form[s.label].indexOf(s.value) == -1) {
                flag.push(false)
              } else {
                flag.push(true)
              }
              break
            case '为空':
              if (this.form[s.label]) {
                flag.push(false)
              } else {
                flag.push(true)
              }
              break
            case '不为空':
              if (!this.form[s.label]) {
                flag.push(false)
              } else {
                flag.push(true)
              }
              break
          }
        })
        if (m.link == '所有') {
          if (flag.length > 0 && flag.findIndex((target) => target === false) == -1) {
            all.map((r) => {
              m.show.map((y) => {
                if (r.prop == y) {
                  r.display = true
                }
              })
            })
          } else {
            all.map((r) => {
              m.show.map((y) => {
                if (r.prop == y) {
                  r.display = false
                }
              })
            })
          }
        } else {
          if (flag.indexOf(true) != -1) {
            all.map((r) => {
              m.show.map((y) => {
                if (r.prop == y) {
                  r.display = true
                }
              })
            })
          } else {
            all.map((r) => {
              m.show.map((y) => {
                if (r.prop == y) {
                  r.display = false
                }
              })
            })
          }
        }
      })
    },
    //规则设置
    setRule(data, callback) {
      if (data.initDataUrl && data.initDataType) {
        // eslint-disable-next-line @typescript-eslint/no-this-alias
        var that = this
        getAction(data.initDataUrl).then((response) => {
          eval(data.initDataDetail)
        })
      }
      if (data.showRule && data.showRule.length > 0) {
        // 设置默认隐藏参数
        let hideData = []
        let condition = [] //规则
        let detail = {}

        data.showRule.forEach((e) => {
          hideData = hideData.concat(e.showValue)
          e.rule[0].children.map((q) => {
            if (detail[q.label]) {
              e.rule[0]['show'] = e.showValue
              detail[q.label].push(e.rule[0])
              detail[q.label] = [...new Set(detail[q.label])]
            } else {
              detail[q.label] = []
              e.rule[0]['show'] = e.showValue
              detail[q.label].push(e.rule[0])
            }
          })

          data.column.map((q) => {
            if (hideData.indexOf(q.prop) != -1) {
              q.display = false
            }
            if (detail[q.prop]) {
              q.change = (val) => {
                if (val.value) {
                  setTimeout(() => {
                    this.setDatail(detail[q.prop], [...data.column, ...data.group])
                  }, 100)
                }
              }
            }
          })
          if (data.group)
            data.group.map((q) => {
              if (hideData.indexOf(q.prop) != -1) {
                q.display = false
              }
              if (detail[q.prop]) {
                q.change = (val) => {
                  if (val.value) {
                    setTimeout(() => {
                      this.setDatail(detail[q.prop], [...data.column, ...data.group])
                    }, 100)
                  }
                }
              }
            })
        })
      }
      callback(data)
    },
    setBtn(ret) {
      if (ret)
        if (ret.method == 'get') {
          getAction(ret.url).then((res) => {
            const response = this.getAsVal(res, ret.resKey || 'data.data')
            if (!response) this.$message.error('未查询到数据或者返回层级配置错误')
            const records = this.getAsVal(response, ret.recordsKey || 'list')
            for (var i in records) {
              this.form[i] = records[i]
            }
          })
        } else {
          let obj = {}
          if (ret.dicData) {
            ret.dicData.map((e) => {
              obj[e.key] =
                e.value.indexOf('&{') != -1 ? this.form[e.value.match(/&{(\S*)}/)[1]] : e.value
            })
          }
          postAction(ret.url, obj).then((res) => {
            const response = this.getAsVal(res, ret.resKey || 'data.data')
            if (!response) this.$message.error('未查询到数据或者返回层级配置错误')
            const records = this.getAsVal(response, ret.recordsKey || 'list')
            for (var i in records) {
              this.form[i] = records[i]
            }
          })
        }
    },
    checkFlagChild(data, callback) {
      // 处理组件方法挂载
      const compArr = getJsonCallableCompListWithChildren(data)
      compArr.map((e)=>{
        this.allEventsByComps.forEach((event)=>{
            if(e[event] && typeof e[event] == 'string'){
              e[event] = eval(e[event])
            }else if(e[`_${event}`] && typeof e[`_${event}`] == 'object'){
              const { params, components } = e[`_${event}`];
              // 挂载调用函数,这里不能使用箭头函数，调用时this必须是组件自己的实例对象
              e[event] = function(){
                executeFunctionsInOrderByParamsSetting(this, params, components, true)
              }
              delete e[`_${event}`]
          }
        })
      })
      if (data.column)
        data.column.forEach((e) => {
          // if (e.change && typeof e.change == 'string') {
          //   // eslint-disable-next-line @typescript-eslint/no-this-alias
          //   var that = this
          //   e.change = eval(e.change)
          // }

          // if (e.click && typeof e.click == 'string') {
          //   // eslint-disable-next-line @typescript-eslint/no-this-alias
          //   var that = this
          //   e.click = eval(e.click)
          // }

          // if (e.focus && typeof e.focus == 'string') {
          //   // eslint-disable-next-line @typescript-eslint/no-this-alias
          //   var that = this
          //   e.focus = eval(e.focus)
          // }

          // if (e.blur && typeof e.blur == 'string') {
          //   // eslint-disable-next-line @typescript-eslint/no-this-alias
          //   var that = this
          //   e.blur = eval(e.blur)
          // }

          // if (e.appendClick && typeof e.appendClick == 'string') {
          //   // eslint-disable-next-line @typescript-eslint/no-this-alias
          //   var that = this
          //   e.appendClick = eval(e.appendClick)
          // }

          // if (e.control && typeof e.control == 'string') {
          //   // eslint-disable-next-line @typescript-eslint/no-this-alias
          //   var that = this
          //   e.control = eval(e.control)
          // }

          // if (e.onLoad && typeof e.onLoad == 'string') {
          //   // eslint-disable-next-line @typescript-eslint/no-this-alias
          //   var that = this
          //   e.onLoad = eval(e.onLoad)
          //   // e.onLoad = this.setVal(e);
          // }

          // if (e.uploadAfter && typeof e.uploadAfter == 'string') {
          //   // eslint-disable-next-line @typescript-eslint/no-this-alias
          //   var that = this
          //   e.uploadAfter = eval(e.uploadAfter)
          // }

          if (e.type == 'primary' || e.type == 'text') {
            if (e.click) {
              // eslint-disable-next-line @typescript-eslint/no-this-alias
              var that = this
              e.event = {
                click: e.click
              }
            } else {
              if (e.buttonType == '自定义') {
                e.event = {
                  click: () => {
                    this.setBtn(e)
                  }
                }
              } else {
                if (e.association && e.associationKey) {
                  e.event = {
                    click: () => {
                      getForm(e.associationKey).then((response) => {
                        const { data } = response.data
                        this.option2 = JSON.parse(data.expand)
                        this.previewVisibleChild = true
                      })
                    }
                  }
                }
              }
            }
          }

          if (e.association) {
            if (e.type == 'dynamic') {
              this.oldNum[e.prop] = 0
              e.change = (t) => {
                if (t.value.length > 0) {
                  if (this.oldNum[e.prop] < t.value.length) {
                    getForm(e.associationKey).then((response) => {
                      const { data } = response.data
                      this.option2 = JSON.parse(data.expand)
                      this.previewVisibleChild = true
                      this.oldNum[e.prop] = t.value.length
                    })
                  } else {
                    this.oldNum[e.prop] = t.value ? t.value.length : 0
                  }
                } else {
                  this.oldNum[e.prop] = 0
                }
              }
            } else {
              e.click = () => {
                getForm(e.associationKey).then((response) => {
                  const { data } = response.data
                  this.option2 = JSON.parse(data.expand)
                  this.previewVisibleChild = true
                })
              }
            }
          }
        })
      if (data.group)
        data.group.forEach((q) => {
          q.column.forEach((e) => {
            // if (e.change && typeof e.change == 'string') {
            //   // eslint-disable-next-line @typescript-eslint/no-this-alias
            //   var that = this
            //   e.change = eval(e.change)
            // }

            // if (e.click && typeof e.click == 'string') {
            //   // eslint-disable-next-line @typescript-eslint/no-this-alias
            //   var that = this
            //   e.click = eval(e.click)
            // }

            // if (e.focus && typeof e.focus == 'string') {
            //   // eslint-disable-next-line @typescript-eslint/no-this-alias
            //   var that = this
            //   e.focus = eval(e.focus)
            // }

            // if (e.blur && typeof e.blur == 'string') {
            //   // eslint-disable-next-line @typescript-eslint/no-this-alias
            //   var that = this
            //   e.blur = eval(e.blur)
            // }

            // if (e.appendClick && typeof e.appendClick == 'string') {
            //   // eslint-disable-next-line @typescript-eslint/no-this-alias
            //   var that = this
            //   e.appendClick = eval(e.appendClick)
            // }

            // if (e.control && typeof e.control == 'string') {
            //   // eslint-disable-next-line @typescript-eslint/no-this-alias
            //   var that = this
            //   e.control = eval(e.control)
            // }

            // if (e.onLoad && typeof e.onLoad == 'string') {
            //   // eslint-disable-next-line @typescript-eslint/no-this-alias
            //   var that = this
            //   e.onLoad = eval(e.onLoad)
            //   // e.onLoad = this.setVal(e);
            // }

            // if (e.uploadAfter && typeof e.uploadAfter == 'string') {
            //   // eslint-disable-next-line @typescript-eslint/no-this-alias
            //   var that = this
            //   e.uploadAfter = eval(e.uploadAfter)
            // }

            if (e.type == 'primary' || e.type == 'text') {
              if (e.click) {
                // eslint-disable-next-line @typescript-eslint/no-this-alias
                var that = this
                e.event = {
                  click: e.click
                }
              } else {
                if (e.buttonType == '自定义') {
                  e.event = {
                    click: () => {
                      this.setBtn(e)
                    }
                  }
                } else {
                  if (e.association && e.associationKey) {
                    e.event = {
                      click: () => {
                        getForm(e.associationKey).then((response) => {
                          const { data } = response.data
                          this.option2 = JSON.parse(data.expand)
                          this.previewVisibleChild = true
                        })
                      }
                    }
                  }
                }
              }
            }
            if (e.association) {
              if (e.type == 'dynamic') {
                this.oldNum[e.prop] = 0
                e.change = (t) => {
                  if (t.value.length > 0) {
                    if (this.oldNum[e.prop] < t.value.length) {
                      getForm(e.associationKey).then((response) => {
                        const { data } = response.data
                        this.option2 = JSON.parse(data.expand)
                        this.previewVisibleChild = true
                        this.oldNum[e.prop] = t.value.length
                      })
                    } else {
                      this.oldNum[e.prop] = t.value ? t.value.length : 0
                    }
                  } else {
                    this.oldNum[e.prop] = 0
                  }
                }
              } else {
                e.click = (ev) => {
                  getForm(e.associationKey).then((response) => {
                    const { data } = response.data
                    this.option2 = JSON.parse(data.expand)
                    this.previewVisibleChild = true
                  })
                }
              }
            }
          })
        })
      callback()
    },
    initialization(val) {
      if (this.seeData == '1') {
        searchForm(this.pageVersionId).then((res) => {
          let { pageFormJson } = res.data
          if(isBase64(pageFormJson)){
            pageFormJson = Base64.decode(pageFormJson)
          }
          // 处理符号保存到后端转义导致的问题，先转化回来
          const data = specialSignTrans(pageFormJson)
          this.iJson1 = JSON.parse(data)
          this.formId = res.data ? res.data.pageFormId : ''
          this.$emit('formId', this.formId, this.formData)
          this.handleImportJsonSubmit()
        })
      } else {
        this.importJson = val
        this.handleImportJsonSubmit()
      }
    },
    // 导入JSON - 弹窗 - 确定
    handleImportJsonSubmit() {
      let params = this.seeData == '1' ? this.iJson1 : this.importJson
      // params.column = this.widgetColumn
      try {
        this.transAvueOptionsToFormDesigner(params).then((res) => {
          if (Object.keys(res).length) {
            // 处理string形式的function
            this.handleEventsTransform(res)
            this.widgetForm = res
          } else {
            this.widgetForm.column = cloneDeep(this.formData.column)
          }
          this.importJsonVisible = false
          this.handleHistoryChange(this.widgetForm)
        })
      } catch (e) {
        this.$message.error(e.message)
      }
    },
    // 生成JSON - 弹窗
    handleGenerateJson() {
      this.transformToAvueOptions(this.widgetForm).then((data) => {
        this.option = JSON.stringify(data)
        this.generateJsonVisible = true
      })
    },
    // 生成JSON - 弹窗 - 确定
    handleGenerate() {
      this.transformToAvueOptions(this.widgetForm).then((data) => {
        if (this.configOption.generateType && this.configOption.generateType == 'string')
          this.$emit(
            'submit',
            beautifier(data, {
              minify: true,
              ...this.configOption
            })
          )
        else this.$emit('submit', data)
      })
    },
    // 生成JSON - 弹窗 - 拷贝
    handleCopy() {
      this.transformToAvueOptions(this.widgetForm).then((data) => {
        this.$Clipboard({
          text: beautifier(data, {
            minify: true,
            ...this.configOption
          })
        })
          .then(() => {
            this.$message.success('复制成功')
          })
          .catch(() => {
            this.$message.error('复制失败')
          })
      })
    },
    // 预览 - 弹窗 - 确定
    handlePreviewSubmit(form, done) {
      if (done) {
        this.$alert(this.form)
          .then(() => {
            done()
          })
          .catch(() => {
            done()
          })
      } else {
        this.$refs.form.validate((valid, done) => {
          if (valid)
            this.$alert(this.form)
              .then(() => {
                done()
              })
              .catch(() => {
                done()
              })
        })
      }
    },
    handleSelectionChange() {},
    // 预览 - 弹窗 - 关闭前
    handleBeforeClose() {
      if(this.$refs.form){
        this.$refs.form.resetForm()
      }
      this.form = {}
      this.previewVisible = false
    },

    // 预览 - 弹窗 - 确定
    // handlePreviewSubmit2(form, done) {
    //   if (done) {
    //     this.$alert(this.form2).then(() => {
    //       done()
    //     }).catch(() => {
    //       done()
    //     })
    //   } else {
    //     this.$refs.form2.validate((valid, done) => {
    //       if (valid) this.$alert(this.form2).then(() => {
    //         done()
    //       }).catch(() => {
    //         done()
    //       })
    //     })
    //   }
    // },
    // 预览 - 弹窗 - 关闭前
    // handleBeforeClose2() {
    //   this.$refs.form2.resetForm()
    //   this.form2 = {}
    //   this.previewVisibleChild = false
    // },

    // 清空
    handleClear() {
      if (this.widgetForm && this.widgetForm.column && this.widgetForm.column.length > 0) {
        this.$confirm('确定要清空吗？', '警告', {
          type: 'warning'
        })
          .then(() => {
            this.widgetForm.column = []
            this.form = {}
            this.widgetFormSelect = {}
            // this.$set(this.widgetForm, 'column', [])
            // this.$set(this, 'form', {})
            // this.$set(this, 'widgetFormSelect', {})
            this.handleHistoryChange(this.widgetForm)
          })
          .catch(() => {})
      } else this.$message.error('没有需要清空的内容')
    },
    // 表单设计器配置项 转化为 Avue配置项
    transformToAvueOptions(obj, isPreview = false) {
      // eslint-disable-next-line @typescript-eslint/no-this-alias
      const _this = this
      function toApi(type, url, data, callback) {
        if (type == 'get') {
          getAction(url, data).then((res) => {
            callback(res)
          })
        } else {
          postAction(url, data).then((res) => {
            callback(res)
          })
        }
      }
      return new Promise((resolve, reject) => {
        try {
          const data = _this.deepClone(obj)
          for (let key in data) {
            if (validatenull(data[key])) delete data[key]
          }
          for (let i = 0; i < data.column.length; i++) {
            const col = data.column[i]

            if (isPreview) {
              // 预览调整事件中的this指向
              // let event = ['change', 'blur', 'click', 'focus', 'uploadAfter', 'uploadBefore']
              _this.allEventsByComps.forEach((e) => {
                if (col[e]) col[e] = eval((col[e] + '').replace(/this/g, '_this'))
              })
              if (col.event)
                Object.keys(col.event).forEach(
                  (key) => (col.event[key] = eval((col.event[key] + '').replace(/this/g, '_this')))
                )
            }

            if (
              col.type == 'dynamic' &&
              col.children &&
              col.children.column &&
              col.children.column.length > 0
            ) {
              const c = col.children.column
              c.forEach((item) => {
                delete item.subfield
              })
              this.transformToAvueOptions(col.children, isPreview).then((res) => {
                col.children = res
              })
            } else if (col.type == 'group') {
              if (!data.group) data.group = []
              const group = {
                label: col.label,
                icon: col.icon,
                prop: col.prop,
                arrow: col.arrow,
                collapse: col.collapse,
                display: col.display
              }
              this.transformToAvueOptions(col.children, isPreview).then((res) => {
                group.column = res.column
                data.group.push(group)
              })
              data.column.splice(i, 1)
              i--
            } else if (col.type == 'grid') {
              col.rows.map((item, idx) => {
                this.transformToAvueOptions(item, isPreview).then((res) => {
                  col.rows[idx] = res
                })
              })
            } else if (['checkbox', 'radio', 'tree', 'cascader', 'select'].includes(col.type)) {
              if (col.dicOption == 'static') {
                delete col.dicQuery

                // debugger
                const { label, value, desc } = col.props || col.prop
                col.dicData.forEach((d) => {
                  if (d.label) {
                    const val = d.label
                    delete d.label
                    d[label] = val
                  }
                  if (d.value) {
                    const val = d.value
                    delete d.value
                    d[value] = val
                  }
                  if (d.desc) {
                    const val = d.desc
                    delete d.desc
                    d[desc] = val
                  }
                })
              } else if (col.dicOption == 'remote') {
                delete col.dicData
                if (col.dicQueryConfig && col.dicQueryConfig.length > 0) {
                  const query = {}
                  col.dicQueryConfig.forEach((q) => {
                    if (q.key && q.value) query[q.key] = q.value
                  })
                  col.dicQuery = query
                } else {
                  delete col.dicQuery
                }
              }
              delete col.dicQueryConfig
              // delete col.dicOption;
            } else if (['upload'].includes(col.type)) {
              const { ajaxSetting } = col
              if(ajaxSetting){
                if (ajaxSetting.headers && ajaxSetting.headers.length > 0) {
                const headers = {}
                ajaxSetting.headers.forEach((h) => {
                  if (h.key && h.value) headers[h.key] = h.value
                })
                col.headers = headers
              } else delete col.headers

              if (ajaxSetting.params && ajaxSetting.params.length > 0) {
                const data = {}
                ajaxSetting.params.forEach((h) => {
                  if (h.key && h.value) data[h.key] = h.value
                })
                col.data = data
              } else delete col.data
              }
            }
            for (let key in col) {
              if (validatenull(col[key])) delete col[key]
            }
          }
          resolve(data)
        } catch (e) {
          reject(e)
        }
      })
    },
    formatTime(...args) {
      try {
        // 参数解构
        const [a, b] = args
        // 默认值
        let dt = new Date(), //默认当前时间
          ft = 'YYYY-MM-DD HH:mm:ss' // 默认格式
        //如果参数只传入了一个的情况，我们认为用户用户传入的是格式，需要格式化的是当前时间
        if (args.length == 1) {
          if (isNaN(new Date(a).valueOf())) {
            ft = a
          } else {
            dt = new Date(typeof a == 'string' && a.includes('-') ? a.replace(/-/g, '/') : a)
          }
        } else if (args.length >= 2) {
          dt = new Date(typeof a == 'string' && a.includes('-') ? a.replace(/-/g, '/') : a)
          ft = b
        }
        const map = {
          Y: String(dt.getFullYear()), //4位数 年份
          M: String(dt.getMonth() + 1).padStart(2, 0), // 2位数 月份
          D: String(dt.getDate()).padStart(2, 0), // 2位数 日期
          H: String(dt.getHours()).padStart(2, 0), // 2位数 时
          m: String(dt.getMinutes()).padStart(2, 0), // 2位数 分
          s: String(dt.getSeconds()).padStart(2, 0), //2位数 秒
          S: String(dt.getMilliseconds()).padStart(3, 0), // 3位数 毫秒
          Q: Math.floor((dt.getMonth() + 3) / 3) + '' //季度
        }
        return ft.replace(
          /\[([^\]]+)]|y{1,4}|Y{1,4}|M{1,2}|d{1,2}|D{1,2}|h{1,2}|H{1,2}|m{1,2}|s{1,2}|q|t|S{1,3}/g,
          (match) => {
            // 匹配中的首字符
            let k = match[0]
            // 匹配到的字符串长度
            let len = match.length
            switch (k) {
              case 'y':
              case 'Y':
                return match.replace(new RegExp('((' + k + ')+)', 'g'), (a) =>
                  map.Y.substr(4 - a.length)
                )
              case 'M':
                return len == 1 ? Number(map.M) : map.M
              case 'D':
              case 'd':
                return len == 1 ? Number(map.D) : map.D
              case 'H':
              case 'h':
                return len == 1 ? Number(map.H) : map.H
              case 'm':
                return len == 1 ? Number(map.m) : map.m
              case 's':
                return len == 1 ? Number(map.s) : map.s
              case 'S':
                return match.replace(new RegExp('((' + k + ')+)', 'g'), (a) =>
                  map.S.substr(3 - a.length)
                )
              case '[':
                return match.replace(/\[|\]/g, '')
              case 'q':
                return map.Q
              default:
                return match
            }
          }
        )
      } catch (e) {
        return new Date('') // Invalid Date
      }
    },
    // Avue配置项 转化为 表单设计器配置项
    transAvueOptionsToFormDesigner(obj) {
      if (typeof obj == 'string') {
        // let [clickStartIndex, changeStartIndex, end, value, controlStartIndex] = [[], [], [], [], []];
        //
        //
        // for (const match of obj.matchAll(/click/g)) {
        //   clickStartIndex.push(match.index)
        // }
        // for (const match2 of obj.matchAll(/change/g)) {
        //   changeStartIndex.push(match2.index)
        // }
        //
        // for (const match4 of obj.matchAll(/control/g)) {
        //   controlStartIndex.push(match4.index)
        // }
        //
        // for (const match3 of obj.matchAll(/,/g)) {
        //   end.push(match3.index)
        // }
        //
        //
        // end.forEach((e, index) => {
        //   clickStartIndex.forEach((s) => {
        //     if (s > end[index - 1] && s < e) {
        //       value.push((obj.slice(s, e)))
        //     }
        //   })
        //   changeStartIndex.forEach((s) => {
        //     if (s > end[index - 1] && s < e) {
        //       value.push((obj.slice(s, e)))
        //     }
        //   })
        //   controlStartIndex.forEach((s) => {
        //     if (s > end[index - 1] && s < end) {
        //       value.push((obj.slice(s, e)))
        //     }
        //   })
        // })
        //
        //
        // console.log(value)
        //
        // value.forEach((t) => {
        //   obj = obj.replace(t , '')
        // })

        obj = eval('(' + obj + ')')
      }
      const data = this.deepClone(obj)
      return new Promise((resolve, reject) => {
        try {
          if (data.column && data.column.length > 0) {
            data.column.forEach((col) => {
              if (
                (col.type == 'dynamic' || col.type == 'anvilDynamic') &&
                col.children &&
                col.children.column &&
                col.children.column.length > 0
              ) {
                const c = col.children.column
                c.forEach((item) => {
                  item.subfield = true
                })
                this.transAvueOptionsToFormDesigner(col.children).then((res) => {
                  col.children = res
                })
              } else if (
                ['checkbox', 'radio', 'tree', 'cascader', 'select', 'text', 'primary'].includes(
                  col.type
                )
              ) {
                if (!col.dicData && col.dicQuery && typeof col.dicQuery == 'object') {
                  const arr = []
                  for (let key in col.dicQuery) {
                    arr.push({
                      key,
                      value: col.dicQuery[key],
                      $cellEdit: true
                    })
                  }
                  col.dicQueryConfig = arr
                } else if (col.dicOption == 'remote' && !col.dicQuery) {
                  col.dicQueryConfig = []
                }
                // if (col.dicUrl || col.formDataUrl) col.dicOption = 'remote'
                // else col.dicOption = 'static'
                if (!col.dicData) col.dicData = []
                else if (col.props) {
                  col.dicData.forEach((d) => {
                    const { label, value, desc } = col.props
                    if (label) {
                      const val = d[label]
                      delete d[label]
                      d.label = val
                    }
                    if (value) {
                      const val = d[value]
                      delete d[value]
                      d.value = val
                    }
                    if (desc) {
                      const val = d[desc]
                      delete d[desc]
                      d.desc = val
                    }
                  })
                }
              } else if (['upload'].includes(col.type)) {
                // 因数据结构变化无需处理
                // if (col.headers && typeof col.headers == 'object') {
                //   const arr = []
                //   for (let key in col.headers) {
                //     arr.push({
                //       key,
                //       value: col.headers[key],
                //       $cellEdit: true
                //     })
                //   }
                //   col.headersConfig = arr
                // } else col.headersConfig = []

                // if (col.data && typeof col.data == 'object') {
                //   const arr = []
                //   for (let key in col.data) {
                //     arr.push({
                //       key,
                //       value: col.data[key],
                //       $cellEdit: true
                //     })
                //   }
                //   col.dataConfig = arr
                // } else col.dataConfig = []
              } else if (col.type.includes('grid')) {
                col.rows.map((item, idx) => {
                  this.transAvueOptionsToFormDesigner(item).then((res) => {
                    col.rows[idx] = res
                  })
                })
              }
            })
          }
          if (data.group && data.group.length > 0) {
            for (let i = 0; i < data.group.length; i++) {
              if (!data.column) data.column = []
              const col = data.group[i]

              const group = {
                type: 'group',
                label: col.label,
                icon: col.icon,
                prop: col.prop,
                arrow: col.arrow,
                collapse: col.collapse,
                display: col.display
              }
              this.transAvueOptionsToFormDesigner(col).then((res) => {
                group.children = res
                data.column.push(group)
              })
            }
            delete data.group
          }
          resolve(data)
        } catch (e) {
          reject(e)
        }
      })
    },
    async getData(type = 'json', option = {}) {
      if (type == 'string')
        return beautifier(await this.transformToAvueOptions(this.widgetForm), {
          minify: true,
          ...option
        })
      else if (type == 'app') {
        const option = await this.transformToAvueOptions(this.widgetForm)
        this.parseJson(option)
        return option
      } else {
        const res = await this.transformToAvueOptions(this.widgetForm)
        this.handleEventsTransform2String(res)
        return res
      }
    },
    parseJson(jsonObj) {
      // 循环所有键
      for (var key in jsonObj) {
        //如果对象类型为object类型且数组长度大于0 或者 是对象 ，继续递归解析
        var element = jsonObj[key]
        if (
          (element && element.length > 0 && typeof element == 'object') ||
          typeof element == 'object'
        ) {
          this.parseJson(element)
        } else if (typeof element == 'function') {
          jsonObj[key] = element + ''
        }
      }
    },
    // 处理所有事件方法的调用转化
    handleEventsTransform2String(obj) {
      // const events = ['change', 'click', 'focus', 'blur', 'appendClick', 'control', 'uploadBefore', 'uploadAfter']
      const list = obj.column || []
      list.forEach((item) => {
        this.allEventsByComps.forEach((event)=>{
          if(item[event] && typeof item[event] == 'function'){
            item[event] = String(item[event])
          }
        })
      })
    },
    handleEventsTransform(obj) {
      // const events = ['change', 'click', 'focus', 'blur', 'appendClick', 'control', 'uploadBefore', 'uploadAfter']
      const list = obj.column || []
      list.forEach((item) => {
        this.allEventsByComps.forEach((event)=>{
          if(item[event] && typeof item[event] == 'string'){
            const func = function (fnStr) {
              // 先对str做转义处理
              const str = fnStr.replaceAll('&gt;', '>')
              // return eval('(' + str + ')')
              return str
            }
            item[event] = func(item[event])
          }
        })
      })
    },
    // 提取非系统字段
    filterFieldsNotSystem(field, columns, isPush) {
      if (field.children) {
        const { children } = field
        const { column } = children
        if (column) {
          const col = column.filter((child) => {
            return this.filterFieldsNotSystem(child, columns, false)
          })
          field.children.column = col
          if (isPush) {
            columns.push(field)
          }
        }
      } else if (field.isSystem == 'N' || field.isSystem == undefined) {
        if (field.dataType == 'varchar') {
          field.icon = 'icon-input'
        } else if (field.dataType == 'bigint') {
          field.icon = 'icon-number'
        } else if (field.dataType == 'number' || field.dataType == 'decimal') {
          field.icon = 'icon-number'
        } else if (field.dataType == 'datetime') {
          field.icon = 'icon-datetime'
        } else if (field.dataType == 'text') {
          field.icon = 'icon-textarea'
        } else if (field.dataType == 'select') {
          field.icon = 'el-icon-edit'
        } else if (field.dataType == 'radio') {
          field.icon = 'icon-radio'
        } else if (field.dataType == 'multiple') {
          field.icon = 'icon-checkbox'
        }
        if (isPush) {
          columns.push(field)
        }
        return true
      }
    },
    // 筛选是否为支持app组件
    isAppComp(comp) {
      if (this.forApp) {
        // const res = this.appCompDicts.find((item) => item.dictLabel == type);
        return comp.isApp == 'Y'
      } else {
        return true
      }
    },
    // 校验组件中是否有支持app组件
    checkExistAppComp(list) {
      if (this.forApp) {
        const res = list.filter((comp) => {
          return this.isAppComp(comp)
        })
        if (res.length) {
          return true
        } else {
          return false
        }
      } else {
        return true
      }
    },
    // 单独处理逻辑，在新建场景时保存表单设计之后返回，调用接口获取
    // 如果seedata为2，说明组件json是从父组件传过来的，直接接收并返回即可
    getFormJsonEchoByAdd() {
      if (this.seeData == '0') {
        searchForm(this.pageVersionId).then((res) => {
          if (res && res.data) {
            let { pageFormJson } = res.data
            if(isBase64(pageFormJson)){
              pageFormJson = Base64.decode(pageFormJson)
            }
            // 处理符号保存到后端转义导致的问题，先转化回来
            const data = specialSignTrans(pageFormJson)
            const Json = JSON.parse(data)
            this.initialization(Json)
          }
        })
      } else if (this.seeData == '2') {
        this.initialization(JSON.parse(this.formJson))
      }
    },
    // 处理draggable拖拽后组件编辑不影响原组件
    clone(obj) {
      return cloneDeep(obj)
    },
    // 获取模版组件列表
    async getTemplateCompList() {
      return searchTemplateCompList().then((res) => {
        return res.data
      })
    },
    async getCompositeCompList() {
      return searchCompositeCompList().then((res) => {
        return res.data
      })
    },
    // 根据实体获取字段列表
    getAttrsByEntity() {
      this.attrList = []
      const { pageModelId } = this.formModelDataFromDesign
      const ids = pageModelId.join(',')
      return getModelEntityTreeByids(ids).then((res) => {
        if (res.code == '200') {
          this.attrList = res.data
          this.appendDescName(this.attrList)
        }
      })
    },
    appendDescName(list) {
      list.forEach((item) => {
        item.entityDescName = `${item.entityDesc}(${item.entityName})`
        if (item.childList && item.childList.length > 0) {
          this.appendDescName(item.childList)
        }
      })
    },
    getAllEventsByComps(){
      const events = []
      for(let name in EventsMap){
        const e = EventsMap[name].map(item=>item.value)
        events.push(...e)
      }
      this.allEventsByComps = [...new Set(events)]
    },
    handleFieldDragStart(e,index){
      const { oldIndex } = e
      const field = this.fields[index].list[oldIndex]
      const { span } = field
      const { setCurDragField } = useCodeStore()
      setCurDragField(field)
    },
    // aigc接口调用
    openAIGC(){
      ElMessageBox.prompt('请输入页面描述','AIGC页面生成', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      }).then(({value})=>{
        ElLoading.service({fullscreen: true})
        const api_url = 'http://192.168.218.205/v1/workflows/run'
        const api_key = "app-10NkFrver1lDBHTvhUUnkuk7"

        const headers = {
            Authorization: 'Bearer ' + api_key,
            'Content-Type': 'application/json'
        }

        const data = {
          inputs: {
            task: value,
            option: "控件清单"
          },
          response_mode: "blocking",
          user: "abc-123"
        }

        fetch(api_url, {
          method: 'post',
          headers,
          body: JSON.stringify(data)
        }).then((response)=>{
          response.json().then((res)=>{
            console.log('res',res)
            if(res.data.status == 'failed'){
              this.msgError(res.data.error)
              return
            }
            const json = res.data.outputs.body
            const { output } = JSON.parse(json)

            this.importJson = output
          }).catch((e)=>{
            this.msgError(e)
          })
          const loading = ElLoading.service({fullscreen: true})
          loading.close()
        }).catch((e)=>{
          this.msgError(e)
          const loading = ElLoading.service({fullscreen: true})
          loading.close()
        })
      })
    }
  }
}
</script>

<style lang="scss">
@import './styles/index.scss';
</style>
